<template>
	<div id="app">
		<!-- 列表 -->
		<div>
			<button v-show="false" id="initBtn" @click="initScriptlist"></button>
			<el-table :data="openScriptData" stripe style="width: 100%">
				<el-table-column prop="keyword" label="openScript关键字" width="260"></el-table-column>
				<el-table-column prop="items" label="打开资源名称" width="260" :formatter="itemNamesFormatter"></el-table-column>
				<el-table-column prop="scriptEnable" label=" 编辑 && 删除" width="260">
					<template slot-scope="scope">
						<el-button type="primary" icon="el-icon-edit" size="mini" @click="editScript(scope.row)"></el-button>
						<el-button type="primary" icon="el-icon-delete" size="mini" @click="deleteScript(scope.row)"></el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-button type="success" @click="addScriptDialogVisible">新增脚本</el-button>
		</div>

		<!-- 新增script对话框 -->
		<el-dialog title="NewLocalOpenScript" :visible.sync="newScriptDialogVisible" width="100%" center  @close="closeDialog">
			<div>
				<el-form :model="script" :rules="scriptFormRules" ref="scriptForm" label-width="100px" class="demo-ruleForm">
					<el-form-item label="关键字:" prop="keyword">
						<el-input  placeholder="脚本关键字,例如:打开工作软件" v-model="script.keyword" width="180"></el-input>
					</el-form-item>
					
					<span  v-for="(item,index) in script.items"  v-bind:key="index" >
						<el-card shadow="hover"  border-radius="4px" >
							<div slot="header" class="clearfix">
							    <span>打开资源：</span>
							    <el-button style="float: right; padding: 3px 0" type="text" @click="deleteResourceItem(index)">删除</el-button>
							  </div>
							<el-form-item label="名称：" :prop="'items.'+index+'.name'" :rules="[{required:true,message:'请输入资源名',trigger:'blur'}]">
								<el-input width="180" placeholder="资源名称 这个名称会在设置页的'打开资源名称'中显示" v-model="item.name" ></el-input>
							</el-form-item>
							<el-form-item label="绝对路径：" :prop="'items.' + index + '.fullPath'" :rules="[{required:true,message:'请输入绝对路径',trigger:'blur'}]">
								<el-input width="180" placeholder="资源绝对路径" v-model="item.fullPath"></el-input>
							</el-form-item>
						</el-card>
					</span>
						
						<el-form-item> 
							<el-button plain icon="el-icon-plus" @click="addResourceItem">新增需要打开的资源条目</el-button>
						</el-form-item>
				</el-form>
			</div>

			<span slot="footer" class="dialog-footer">
				<el-button @click="newScriptDialogCancle">取 消</el-button>
				<el-button type="primary" @click="newScriptDialogSave">保 存</el-button>
			</span>
			
		</el-dialog>

	</div>
</template>

<script>
export default {
	data() {
		return {
			openScriptData: [],
			// dialog
			ifAdd:false,
			newScriptDialogVisible: false,
			script:{
				id:'',
				keyword:'',
				items: []
			},
			scriptFormRules:{
				keyword:[{ required: true, message: '请输入关键字', trigger: 'blur' }],
				items:[{ type: 'array', required: true, message: '请至少添加一个资源', trigger: 'change' }]
			},
			currScript:null
		};
	},
	methods: {
		closeDialog(){
			// 刷新列表
			this.initScriptlist();
		},
		// list
		itemNamesFormatter(row, column, cellValue, index){
			return cellValue.map(item => item.name).join(';');
		},
		addScriptDialogVisible(){
			this.ifAdd = true;
			this.newScriptDialogVisible = true;
			this.emptyDialog()
			this.addResourceItem();
		},
		deleteScript(row){
			// 删除script
			utools.db.remove(row.id);
			// 动态删除feature
			utools.removeFeature(row.id);
			// 刷新列表
			this.initScriptlist();
		},
		editScript(row){
			console.log('row:',row)
			// 更新dialog
			this.script = row;
			// 保存未更改的script  这里不能用this.script直接赋值   会导致 currScript也绑定到一起
			this.currScript = utools.db.get(row.id).data;
			this.ifAdd = false
			this.newScriptDialogVisible = true;
		},
		initScriptlist(){
			this.openScriptData = [];
			// 获取所有文档
			let allDocs = utools.db.allDocs();
			console.log('allDocs:',allDocs)
			if(!allDocs || !allDocs.length) return;
			allDocs.forEach(doc=>{
				let data = doc.data;
				this.openScriptData.push({
					id:doc._id,
					keyword:data.keyword,
					scriptEnable:data.scriptEnable,
					items:data.items,
					rev:doc._rev
				});
			})
		},
		// dialog
		addResourceItem(){
			//name:'',fullPath:''
			this.script.items.push({});
		},
		deleteResourceItem(index){
			this.script.items.splice(index,1)
		},
		newScriptDialogSave(){
			 this.$refs['scriptForm'].validate((valid) => {
				 // CAR
				if(!valid) return;
				if(this.script.items.length == 0) {
					this.$message.error('至少应该添加一个需要打开的资源');
					return;
				}
			
				// Deal
				if(this.ifAdd){// 新增
					// 校验keyword是否已经存在
					if(utools.db.allDocs().find((val)=> {return val.data.keyword === this.script.keyword })) {
						this.$message.error('keyword已存在');
						return;
					}
					// 保存script
					let id = this.openScriptData.length + 1 + '';
					let keyword = this.script.keyword;
					utools.db.put({
					  _id: id,
					  data: {
						  keyword:keyword,
						  scriptEnable:true,
						  items:this.script.items
					  }
					})
					// 动态添加feature
					const featureConf = {
						"code": id,
						"explain": "执行"+keyword+"脚本",
						"cmds":[keyword]
					}
					utools.setFeature(featureConf)
				}else{// 编辑
					// 校验keyword是否已经存在且不是当前keyword
					if(this.currScript && this.currScript.keyword != this.script.keyword
						&& utools.db.allDocs().find((val)=> {return val.data.keyword === this.script.keyword })) {
						this.$message.error('keyword已存在');
						return;
					}
					// 更新script
					let id = this.script.id;
					let keyword = this.script.keyword;
					utools.db.put({
					  _id: id,
					  data: {
						  keyword:keyword,
						  scriptEnable:true,
						  items:this.script.items
					  },
					  _rev: this.script.rev
					});
					// 删除原有的feature 并重新添加
					utools.removeFeature(id)
					const featureConf = {
						"code": id,
						"explain": "执行"+keyword+"脚本",
						"cmds":[keyword]
					}
					utools.setFeature(featureConf)
				}
				// 刷新列表
				this.initScriptlist();
				
				this.newScriptDialogVisible = false;
				this.emptyDialog()
			 });
		},
		newScriptDialogCancle(){
			this.newScriptDialogVisible = false;
		},
		emptyDialog(){
			this.script = {
				id:'',
				keyword:'',
				items: []
			};
			this.currScript = null
		}
	}
};
utools.onPluginEnter(({code, type, payload, optional}) => {
	// 判断code
	if(code === 'localopensetting'){ // 显示设置页面
		console.log('进入设置页面:',code,type,payload, optional);
		document.getElementById('initBtn').click();
	}else{// 进入脚本执行
		console.log('进入脚本执行:',code,type,payload, optional);
		let doc = utools.db.get(code);
		utools.hideMainWindow();
		doc.data.items.forEach(item => {
			let flag = window.openItem(item.fullPath);
			console.log('window.openItem return:',flag);
		});
		utools.outPlugin();
	}
})


</script>

<style>
#app {
	font-family: Helvetica, sans-serif;
	text-align: center;
}
.item-fullPath-input{
	margin-top: 20px;
}
</style>
